<?php

namespace app\index\controller;

use think\Db;
use think\Session;
use think\Request;
use think\Controller;
use think\captcha\Captcha;

class Login extends Controller
{
    public function index()
    {
        return $this->fetch();
    }

    public function doLog()
    {
        $post = Request::instance()->post();
        if (isset($post['username']) && isset($post['password'])) {

            $admin = Db::name('admin')->where('username', $post['username'])->find();

            $captcha = new Captcha();
            if (!$captcha->check($post['captcha'])) {
                $this->error('验证码错误');
            }

            if (!$admin || $admin['password'] !== md5($post['password'])) {
                $this->error('用户名或密码错误');
            }

            Session::set('admin', $admin);
            $this->success('登陆成功', 'index/index');
        }
    }

    public function logOut()
    {
        session(null);
        $this->redirect('login/index');
    }
}
